package sicnu.cs.aps.security.rest;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import sicnu.cs.aps.common.ResultInfoUtil;

import static sicnu.cs.aps.common.util.CollectionUtil.*;

import sicnu.cs.aps.common.util.JwtUtil;
import sicnu.cs.aps.domain.entity.User;
import sicnu.cs.aps.domain.vo.Auth;
import sicnu.cs.aps.service.IUserInfoService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtUtil jwtUtil;
    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        val user = (User) authentication.getPrincipal();
        Auth authToken = jwtUtil.setCookiesForTokens(response, user);
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        log.info(user.toString());
        Map<String, Object> succData = Map.of(
                "userId", user.getId(),
                "username", user.getUsername(),
                "email", user.getEmail(),
                "token", authToken,
                "avatar", user.getAvatar(),
                "mobile", user.getMobile(),
                "authorities", user.getAuthorities());
        response.getWriter().println(objectMapper.writeValueAsString(ResultInfoUtil.buildSuccess(succData)));
    }
}
